package com.liuzhilin.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
/*
* 用户修改个人信息
* */
@WebServlet("/userModifyInformation")
public class UserModifyInformation extends HttpServlet {
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应头，允许跨域请求
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        // 设置响应内容类型为 JSON
        response.setContentType("application/json");
        // 从请求中获取参数
        PrintWriter out = response.getWriter();
        // 从请求体中获取JSON数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            // 将读取的行追加到字符串构建器中
            sb.append(line);
        }
        String json = sb.toString();
        // 解析JSON数据
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将JSON数据转换为Map
            Map<String, String> data = objectMapper.readValue(json, Map.class);
            String username = data.get("username");
            username = username.trim();
            String personalSignature = data.get("personalSignature");
            String birthday = data.get("birthday");
            // 更新数据库用户的个人信息
            boolean success = UserService.modifyUserInformation(username, personalSignature, birthday);

            if (success) {
                out.print("{\"success\": true}");
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "生日错误");
        }
    }
    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        // 设置响应头，允许跨域请求
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
